import express, { Request, Response } from "express";
import path from "path";
import client from "../plugins/oss/client";
import { putBucket } from "../plugins/oss/bucket";
import { unlinkSync } from "../plugins/oss/fs";
import { getUuid } from "../utils/utils";

export default async (req: Request, res: Response) => {
  // 文件组ID
  const { groupId = "" } = req.body;

  // 检查文件是否上传成功
  if (!req?.file) {
    res.status(400).send("No file uploaded");
    return;
  }

  const filename = (req.file as any).filename;
  const localPath = path.join(__dirname, `../../uploads/`, filename);

  try {
    // 设置 文件ID 保存到 meta 中
    const fileId = getUuid();

    // 上传前设置 bucket
    await putBucket();

    // 自定义请求头
    const headers = {
      // // 指定Object的存储类型。
      // "x-oss-storage-class": "Standard",
      // // 指定Object的访问权限。
      // "x-oss-object-acl": "private",
      // // 通过文件URL访问文件时，指定以附件形式下载文件，下载后的文件名称定义为example.txt。
      // "Content-Disposition": 'attachment; filename="example.txt"',
      // // 设置Object的标签，可同时设置多个标签。
      // "x-oss-tagging": "Tag1=1&Tag2=2",
      // // 指定PutObject操作时是否覆盖同名目标Object。此处设置为true，表示禁止覆盖同名Object。
      // "x-oss-forbid-overwrite": "true",
    };

    const meta: any = {
      groupId,
      fileId,
      createdTime: Date.now(),
      name: (req.file as any).originalname,
      size: req.file.size,
    };

    // 上传文件到 Oss，上传成功返回信息
    const ossPath: string = `${groupId}/${fileId}${path.extname(
      (req.file as any).originalname
    )}`;
    const ossSuccessInfo = await client.put(
      ossPath,
      path.normalize(localPath),
      {
        headers,
        meta,
      }
    );

    // 删除本地临时文件
    await unlinkSync(localPath);

    /**
     * 设置返回格式
     */
    res.send({
      code: 0,
      data: [
        {
          url: ossSuccessInfo.url,
          groupId,
          fileId,
          createdTime: Date.now(),
          name: (req.file as any).originalname,
        },
      ],
      msg: "文件上传成功",
    });
  } catch (err) {
    console.log(err);

    // 删除本地图片
    await unlinkSync(localPath);

    res.send({
      code: 500,
      data: null,
      msg: "文件上传失败",
    });
  }
};
